/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.mochaccino.framework.dbtool.impl;

import ch.qos.logback.core.joran.spi.JoranException;
import com.google.code.mochaccino.framework.dbtool.CommandLine;
import com.google.code.mochaccino.framework.dbtool.liquibase.LiquibaseProvider;
import com.google.code.mochaccino.framework.dbtool.liquibase.LiquibaseProviderDS;
import java.io.File;
import java.io.FilenameFilter;
import liquibase.Liquibase;
import liquibase.resource.FileSystemResourceAccessor;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class Patch extends CommandLine {
	private Option OPT_CONTEXTS;
	private Option OPT_DIR;

	private String contexts;
	protected File dir = null;

	/** Constructor */
	public Patch() throws JoranException {
		super();
	}

	@Override
	protected Options createOptions() {
		Options options = new Options();
		options.addOption( OPT_MODULE );
		OPT_CONTEXTS = new Option( "contexts", true, "" );
		OPT_CONTEXTS.setArgName( "CONTEXTS" );
		OPT_CONTEXTS.setRequired( false );
		OPT_CONTEXTS.setArgs( 1 );
		options.addOption( OPT_CONTEXTS );

		OPT_DIR = new Option( "input", true, "" );
		OPT_DIR.setArgName( "DIR" );
		OPT_DIR.setArgs( 1 );
		OPT_DIR.setRequired( false );
		options.addOption( OPT_DIR );

		return options;
	}

	@Override
	protected void execute() {
		LiquibaseProvider provider = new LiquibaseProviderDS( target );
		try {
			provider.initialize();

			File[] files = dir.listFiles( new FilenameFilter() {
				@Override
				public boolean accept( File d, String name ) {
					if ( name.startsWith( FILE_NAME_PREFIX ) && name.endsWith( FILE_NAME_SUFFIX ) ) {
						return true;
					}
					return false;
				}
			} );

			for ( File f : files ) {
				Liquibase b = new Liquibase( f.getAbsolutePath(), new FileSystemResourceAccessor(), provider.getDatabase() );
				if ( contexts != null && contexts.length() == 0 ) {
					contexts = null;
				}
				b.update( contexts );
			}
		} catch ( Exception e ) {
			exit( 2, e );
		} finally {
			try {
				provider.destroy();
			} catch ( Exception e ) {
				exit( 2, e );
			}
		}
	}

	@Override
	protected void interpretArgsBeforeInjection( String[] args ) {
		super.interpretArgsBeforeInjection( args );
		try {
			org.apache.commons.cli.CommandLine parsedArgs = parseArgs( args );
			if ( parsedArgs.hasOption( OPT_CONTEXTS.getOpt() ) ) {
				contexts = parsedArgs.getOptionValue( OPT_CONTEXTS.getOpt() );
			}

			dir = new File( parsedArgs.hasOption( OPT_DIR.getOpt() ) ? parsedArgs.getOptionValue( OPT_DIR.getOpt() ) : DIR );
			if ( !dir.exists() ) {
				if ( !dir.mkdirs() ) {
					exit( 1, "File '" + dir.getAbsolutePath() + "' could not be created" );
				}
			}

			if ( !dir.isDirectory() ) {
				exit( 1, "File '" + dir.getAbsolutePath() + "' is not a directory" );
			}
		} catch ( ParseException e ) {
			exit( 1, e );
		}
	}

	public static final void main( String[] args ) throws JoranException {
		Patch tool = new Patch();
		tool.start( args );
	}
}
